<?php
namespace app\admin\controller;

use think\Controller;
use think\Db;

class Login extends Controller {
	
	public function index(){
		if (session('?backend')){
			$this->redirect('Index/index');
			exit;
		}
		return $this->fetch();
	}
	
	/**
	 * 修改密码发送邮件
	 */
	public function sendemail(){
		$username = $this->request->post('username');
		$email = $this->request->post('email');
		if (empty($username) || empty($email)) exit(json(array('status' => 'error', 'msg' => '用户名或邮箱不能为空'))->getContent());
		$data = db('admin')->where(array('username' => $username,'email' => $email))->find();
		if (empty($data)) exit(json(array('status' => 'error', 'msg' => '用户不存在'))->getContent());
		$time = time();
		$string = $username.$email;
		$token = $this->createToken($time, $string, 'username', 'email');
		$url = url('checkemail',array('token' => _encrypt("{$token}|{$username}|{$email}|{$time}")),true,true);
		$email_tpl_find = db('system')->where(array('name' => 'email_tpl_find'))->find();
		$tmpl = str_replace('{url}', '<a href="'.$url.'" target="_blank">点击此链接</a>', $email_tpl_find['value']);
		if (SendMail($email, '找回密码', $tmpl)){
			exit(json(array('status' => 'success', 'msg' => '请登录邮箱验证邮件'))->getContent());
		}else{
			exit(json(array('status' => 'error', 'msg' => '账号不能为空'))->getContent());
		}
	}
	
	public function checkemail(){
		$token = $this->request->param('token');
		if (empty($token)) $this->error('非法操作');
		$get_token = _encrypt($token,'DECODE');
		list($token,$username,$email,$time) = explode('|', $get_token);
		if (!isset($time) || !isset($token) || !isset($username) || !isset($email)) $this->error('非法操作');
		$diff = time() - $time;
		if ($diff > config('check_email_time')) $this->error('验证邮件已超时',url('index'));
		$string = $username.$email;
		$createToken = $this->createToken($time, $string, 'username', 'email');
		if ($token != $createToken) $this->error('验证失败');
		$data = db('admin')->where(array('username' => $username,'email' => $email))->find();
		if (empty($data)) $this->error('用户不存在');
		$this->assign('data',$data);
		$this->assign('token',$this->request->param('token'));
		return $this->fetch();
	}
	
	private function createToken($time,$string,$delimiter_left,$delimiter_right){
		return md5($delimiter_left.md5($string).$delimiter_right.base64_encode($this->request->ip().$this->request->port()).md5($time));
	}
	
	/**
	 * 修改登录密码
	 */
	public function uplogin(){
		if (!request()->isAjax()){
			exit(json(array('status' => 'error'))->getContent());
		}
		$post_token = _encrypt($this->request->post('token'),'DECODE');
		$username = $this->request->post('username');
		$email = $this->request->post('email');
		$password = $this->request->post('password');
		$netPassword = $this->request->post('netpassword');
		if (!(mb_strlen($password,'utf-8') >= 6 && mb_strlen($password) <= 20)) exit(json(array('status' => 'error', 'msg' => '密码长度6到20位'))->getContent());
		if ($password != $netPassword) exit(json(array('status' => 'error', 'msg' => '两次密码不一致'))->getContent());
		list($token,$username,$email,$time) = explode('|', $post_token);
		if (!isset($time) || !isset($token) || !isset($username) || !isset($email)) exit(json(array('status' => 'error', 'msg' => '非法操作'))->getContent());
		$string = $username.$email;
		$createToken = $this->createToken($time, $string, 'username', 'email');
		if ($token != $createToken) exit(json(array('status' => 'error', 'msg' => '验证用户失败'))->getContent());
		$data = db('admin')->where(array('username' => $username,'email' => $email))->find();
		if ($email == $data['email'] && !empty($data)){
			$data['passsalt'] = create_salt();
			$data['password'] = $netPassword;
			$data['password'] = optimizedSaltPwd($data['password'], $data['passsalt']);
			if (db('admin')->update($data)) exit(json(array('url' => url('index'),'status' => 'success', 'msg' => '密码修改完成'))->getContent());
		}
		
		exit(json(array('status' => 'error', 'msg' => '验证用户失败'))->getContent());

	}
	
	public function ajaxLogin(){
		if (!request()->isAjax()){
			exit(json(array('status' => 'error'))->getContent());
		}
		$username = input('post.username');
		$password = input('post.password');
		if (empty($username)) exit(json(array('status' => 'error', 'msg' => '账号不能为空'))->getContent());
		if (empty($password)) exit(json(array('status' => 'error', 'msg' => '密码不能为空'))->getContent());
		if (_checkemail($username)){
			$map = array('email' => $username);
		}else{
			$map = array('username' => $username);
		}
		$admin = Db::name('admin')->where($map)->find();
		if (empty($admin)) exit(json(array('status' => 'error', 'msg' => '账号或密码不正确'))->getContent());
		if ($admin['password'] != optimizedSaltPwd($password, $admin['passsalt'])){
			exit(json(array('status' => 'error', 'msg' => '账号或密码不正确'))->getContent());
		}
		if (!$admin['status']) exit(json(array('status' => 'error', 'msg' => '账号被禁用'))->getContent());
		
		//保存session
		$session = array(
			'id' => _encrypt($admin['id']),
			'username' => $username,
			'group_id' => $admin['group_id'],
			'login_info' => _encrypt(optimizedSaltPwd($admin['email'].$admin['id'].$admin['mobile'].$admin['username'].$admin['truename'].$_SERVER['HTTP_USER_AGENT'], $admin['passsalt']))
		);
		session('backend',$session);
		//更新登录信息
		$update = array(
			'last_ip' => request()->ip(),
			'last_login_time' => time(),
			'login_count' => $admin['login_count']+1
		);
		Db::name('admin')->where(array('id' => $admin['id']))->update($update);
		echo json(array('status' => 'success','url' => url('Index/index'),'msg' => '登录成功'))->getContent();
	}
	
	//退出后台
	public function logout(){
		session('backend',null);
		session(null);
		$this->redirect('Login/index');
	}
	
}